package com.qs.worklog.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.qs.worklog.dao.UserDAO;
import com.qs.worklog.entity.User;
import com.qs.worklog.util.DataSourceUtil;

public class ImplUserDAO implements UserDAO {

	public boolean saveUser(User user) {
		String sql = "insert into user(name) values(?)";
		try {
			QueryRunner runner =  DataSourceUtil.getQueryRunner();
			runner.update(sql, user.getName());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean deleteUser(String name) {
		String sql = "delete from user where name=?";
		try {
			QueryRunner runner =  DataSourceUtil.getQueryRunner();
			runner.update(sql, name);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public User findUserById(int id) {
		ResultSetHandler<User> h = new BeanHandler<User>(User.class);
		User user = null;
		String sql = "select * from user where id=?";
		try {
			QueryRunner runner =  DataSourceUtil.getQueryRunner();
			user = runner.query(sql, h, id); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	
	public User findUserByName(String name) {
		ResultSetHandler<User> h = new BeanHandler<User>(User.class);
		User user = null;
		String sql = "select * from user where name=?";
		try {
			QueryRunner runner =  DataSourceUtil.getQueryRunner();
			user = runner.query(sql, h, name); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	
	public List<User> findAllUser() {
		String sql = "select * from user";
		ResultSetHandler<List<User>> h = new BeanListHandler<User>(User.class);
		QueryRunner runner =  DataSourceUtil.getQueryRunner();
		List<User> users = null;
		try {
			users = runner.query(sql, h);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return users;
	}
	
}
